<?php
class CProcess {
	/**
	 * 生成随机字符串
	 * @param string $lenth 长度
	 * @return string 字符串
	 */
	public function create_randonstr($lenth = 6){
		return $this->random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');	
	}
	
	/**
	* 产生随机字符串
	* @param    int        $length  输出长度 
	* @param    string     $chars   可选的 ，默认为 0123456789
	* @return   string     字符串
	*/
	public function random($length, $chars = '0123456789'){
		$hash = '';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
		return $hash;
	}
	
	/**
	 * 字符串加密:$runtokey（时间段）.base64_encode($result) 
	 * $result 为要加密的字符串字符的md5后的^
	 */
	public function sys_auth($string, $operation = 'ENCODE', $key = '',$expiry = 0){
		$key_length = 4;
		$key = md5($key != '' ? $key : RonBase::load_config('system', 'auth_key'));
		$fixedkey = md5($key);
		$egiskeys = md5(substr($fixedkey, 16, 16));
		$runtokey = $operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length);
		$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
		$string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry+time() : 0).substr(md5($string.$egiskeys), 0,16).$string : base64_decode(substr($string, $key_length));
		$i = 0; $result = '';
		$string_length = strlen($string);
		for($i = 0; $i < $string_length; $i++){
			$result .= chr(ord($string{$i}) ^ ord($key{$i % 32}));
		}
		if($operation == 'ENCODE'){
			return $runtokey .str_replace('=', '', base64_encode($result)); 
		} else {
			if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
				return substr($result, 26);
			} else {
				return '';
			}
		}
	}
	
	/**
	 * 查找字段拼接
	 */
	public function getSearchFromPost($post){	
		$cond = '';	
		foreach ($post as $k => $v) {
			if(substr_count($k, '_con_')>0){
				$field = str_replace('_con_', '', $k);
				if(substr($field, -3,3) == '_d1'){
					$field_name=substr($field,0,strlen($field)-3);
					$cond .= " and $field_name >= '".strtotime($v)."'";
				} elseif(substr($field, -3,3) == '_d2'){
					$field_name=substr($field,0,strlen($field)-3);
					$cond .= " and $field_name <= '".strtotime($v)."'";
				} else {
					$cond .= " and $field = '$v'";
				}
				
			}			
		}
		return $cond;
	}
}
